/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not
 *  exist, see <http://www.gnu.org/licenses/>.
 *
 * $LastChangedDate: 2008-07-09 23:57:27 +0200 (Wed, 09 Jul 2008) $
 * $Rev: 1282 $
 * $Author: gavinspearhead $
 * $Id: js.js 1282 2008-07-09 21:57:27Z gavinspearhead $
 */

var mousedown = 0;

function init()
{
    // To keep track of the mouse button, used for the quickmenu:
    mousedown = 0;
    document.body.onmousedown = function() { 
        ++mousedown;
        // Sanity check, sometimes it misses ups/downs!
        if (mousedown > 1) { mousedown = 1; }
    };
    document.body.onmouseup = function() {
        --mousedown;
        // Sanity check, sometimes it misses ups/downs!
        if (mousedown < 0) { mousedown = 0; }
    };
}

function GetXmlHttpObject()
{
    var xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (ee) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (xmlHttp === null) {
        alert ("Your browser does not support AJAX!");
        return null;
    } 
    return xmlHttp;
}


function SendXMLHTTPPOST(url,params, action)
{
    var xmlHttp=GetXmlHttpObject();

    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    if (action !== null) {
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
                action(xmlHttp);
            }
        };
    }

    xmlHttp.send(params);
    return xmlHttp;
}


function SendXMLHTTPGET(url,action)
{
    var xmlHttp=GetXmlHttpObject();

    if (action !== null) {
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
                action(xmlHttp);
            }
        };
    }

    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    return xmlHttp;
}

function task_action(action, task, goodmsg, wrongmsg)
{
    var url="action.php";
    var challenge = document.getElementById('challenge_tasks');
    var params = 'cmd='+encodeURIComponent(action)+
        "&challenge="+encodeURIComponent(challenge.value)+
        "&task="+encodeURIComponent(task);
    var xmlHttp=GetXmlHttpObject();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    if (action !== null) {
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
                update_tasks();
                var msg_id = document.getElementById('message_bar');
                if (xmlHttp.responseText == "OK") {
                    msg_id.innerHTML = goodmsg ;
                } else {
                    msg_id.innerHTML = wrongmsg + ': '+ xmlHttp.responseText;
                }

            }
        };
    }
    xmlHttp.send(params);
}

function job_action(action, job, goodmsg, wrongmsg)
{
    var url="action.php";
    var challenge = document.getElementById('challenge_jobs');
    var params = 'cmd='+encodeURIComponent(action)+
        "&challenge="+encodeURIComponent(challenge.value)+
        "&job="+encodeURIComponent(job);
    var xmlHttp=GetXmlHttpObject();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    if (action !== null) {
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
                update_jobs();
                var msg_id = document.getElementById('message_bar');
                if (xmlHttp.responseText == "OK") {
                    msg_id.innerHTML = goodmsg ;
                } else {
                    msg_id.innerHTML = wrongmsg + ': '+ xmlHttp.responseText;
                }

            }
        };
    }
    xmlHttp.send(params);
}

function control_action_confirm(action, goodmsg, wrongmsg, confirmmsg)
{
    var resp = confirm (confirmmsg);
    if (!resp) {return;}
    control_action(action, goodmsg, wrongmsg)

}
function control_action(action, goodmsg, wrongmsg)
{
    var url="action.php";
    var challenge = document.getElementById('challenge_control');
    var params = 'cmd='+action+"&challenge="+challenge.value;
    var xmlHttp=GetXmlHttpObject();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    if (action !== null) {
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) {

                var msg_id = document.getElementById('message_bar');
                if (xmlHttp.responseText == "OK") {
                    msg_id.innerHTML = goodmsg ;
                } else {
                    msg_id.innerHTML = wrongmsg + ': '+ xmlHttp.responseText;
                }

            }
        };
    }
    xmlHttp.send(params);
}

function ng_action_confirm(action, id, goodmsg, wrongmsg, confirmmsg)
{
    var name = document.getElementById("ng_id_" +id);
    if (name == null) return;
    name = name.value;
    confirmmsg = confirmmsg.replace('@@', name);
    var resp = confirm (confirmmsg);
    if (!resp) {return;}
    ng_action(action, id, goodmsg, wrongmsg)

}

function ng_action(action, id, goodmsg, wrongmsg)
{
    var url="action.php";
    var challenge = document.getElementById('challenge1');
    var params = 'cmd='+action+"&group="+id+"&challenge="+challenge.value;
    var xmlHttp=GetXmlHttpObject();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    if (action !== null) {
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
                var msg_id = document.getElementById('message_bar');
                if (xmlHttp.responseText == "OK") {
                    msg_id.innerHTML = goodmsg;
                    //  window.location.reload();
                } else {
                    msg_id.innerHTML = wrongmsg;
                }

            }
        };
    }
    xmlHttp.send(params);
}


function HasClass(item,classname)
{
    var style = item.className;

    // Get all active classes:
    var classList = item.className.split(' ');

    for (var i = 0; i < classList.length; i++) {
        if ( classList[i] == classname ) {
            return true;
        }
    }
    return false;
}

function remove_class(item, classname)
{
    var style = item.className;

    // Get all active classes:
    var classList = item.className.split(' ');
    var removed = 0;
    var newstyle = '';
    for (var i = 0; i < classList.length; i++) {
        if ( classList[i] == classname ) {
            removed = 1;
        } else {
            newstyle = newstyle + ' ' + classList[i];
        }
    }
    item.className = newstyle ; 
}
function add_class(item, classname)
{
    var style = item.className;

    // Get all active classes:
    var classList = item.className.split(' ');
    var newstyle = '';
    for (var i = 0; i < classList.length; i++) {
        if ( classList[i] == classname ) {
        } else {
            newstyle = newstyle + ' ' + classList[i];
        }
    }
    item.className = newstyle + ' ' + classname; 
}

function ToggleClass2(item, classname, old_class)
{
    var style = item.className;

    // Get all active classes:
    var classList = item.className.split(' ');
    var removed = 0;
    var newstyle = '';
    for (var i = 0; i < classList.length; i++) {
        if ( classList[i] == classname ) {
            removed = 1;
        } else {
            newstyle = newstyle + ' ' + classList[i];
        }
    }

    if (removed == 1) {
        item.className = newstyle; // + ' ' + old_class; 
    } else {
        item.className = item.className + ' ' + classname;
    }
}


function ToggleClass(item, classname)
{
    var style = item.className;

    // Get all active classes:
    var classList = item.className.split(' ');

    var removed = 0;
    var newstyle = '';
    for (var i = 0; i < classList.length; i++) {
        if ( classList[i] == classname ) {
            removed = 1;
        } else {
            newstyle = newstyle + ' ' + classList[i];
        }
    }

    if (removed == 1) {
        item.className = newstyle;
    } else {
        item.className = item.className + ' ' + classname;
    }
}


function ToggleClassById(itemname, classname)
{
    var item = document.getElementById(itemname);
    ToggleClass(item,classname);
}


function DisableClass(item, classname)
{
    var style = item.className;

    // Get all active classes:
    var classList = item.className.split(' ');

    //  var removed = 0;
    var newstyle = '';
    for (var i = 0; i < classList.length; i++) {
        if ( classList[i] != classname ) {
            newstyle = newstyle + ' ' + classList[i];
        }
    }
    item.className = newstyle;
}

function EnableClass(item, classname)
{
    var style = item.className;

    // Make sure a class is removed before it is added twice:
    DisableClass(item, classname);

    // Get all active classes:
    var classList = item.className.split(' ');

    /*  
     *   seems to do nothing... at all really
     *  var removed = 0;
     var newstyle = '';
     for (var i = 0; i < classList.length; i++) {
     newstyle = newstyle + ' ' + classList[i];
     }*/
    item.className = item.className + ' ' + classname;
}

function ShowSubMenu(menunr)
{
    var thismenu = document.getElementById('submenu_'+menunr);
    var x = document.getElementsByTagName("table");
    for (var i=0; i < x.length; i++) {
        var subSection = x[i].id.substring(8, 0);  
        if (subSection == "submenu_") {
            if (x[i] == thismenu) {
                DisableClass(x[i],'hidden');
            } else {
                EnableClass(x[i],'hidden');
            }
        }
    }
}
function FastTrim (str) 
{
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}
function UpdateBasketDisplay()
{
    var xmlHttp = GetXmlHttpObject();
    var url = "ajax_processbasket.php";
    var setname =document.getElementById('dlsetname');
    var dlsetname;
    if (setname == null) {
        dlsetname = '';
    }else {
        dlsetname = setname.value;
    }
    var params = "command=view&dlsetname=" + encodeURIComponent(dlsetname);
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            var content = xmlHttp.responseText;
            document.getElementById('basketdiv').innerHTML = content;
            content = FastTrim(content);
            if (content === '') {
                EnableClass(document.getElementById('basketbuttondiv'),'hidden');
            } else {
                DisableClass(document.getElementById('basketbuttondiv'),'hidden');
            }
        }
    };
    xmlHttp.send(params);
}

function SelectSet(setID, type, theevent)
{
    // Remember this set for when the shift key is pressed, so we can toggle everything in between.
    // First see if shift was used and we need to toggle a bunch, before we overwrite the LastClickedSetID.
    // We also need to check if there is a valid LastClickedSetID to prevent bogus stuff.
    if (theevent.shiftKey && typeof(LastClickedSetID) != 'undefined' ) {
    //  alert('toggling from ' + LastClickedSetID + ' to ' + setID);
        ToggleGroupOfSets(LastClickedSetID,setID,type);
    }else{
        ToggleSet(setID, type);
    }
    LastClickedSetID = setID;
}

function ToggleSet(setID, type)
{
    var set = document.getElementById('set_'+setID);
    var rowtd = document.getElementById('td_set_'+setID);
    var button = document.getElementById('big_'+setID);
    var params = '';

    if (set.value === '') {
        xstatus = 0;
        params = "command=add";
    } else {
        xstatus = 1;
        params = "command=del";
    }

    if (xstatus === 0) {
        set.value = 'x';
        button.src = document.getElementById('buttonminus').value;
    } else {
        set.value = "";
        button.src = document.getElementById('buttonplus').value;
    }

    var xmlHttp = GetXmlHttpObject();
    var url = "ajax_processbasket.php";
    params = params + "&setID=" + setID + "&type=" + type;

    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            UpdateBasketDisplay();
        }
    };
    xmlHttp.send(params);
}


function SubmitSearchWithOrder(val)
{
    var orderval = document.getElementById('searchorder');
    if (orderval.value == val) {
        orderval.value = val + ' desc';
    } else {
        orderval.value = val;
    }
    var searchform = document.getElementById('searchform');
    searchform.submit();
}


function submit_sort_log(val)
{
    var orderval = document.getElementById('searchorder');
    var orderdir = document.getElementById('searchdir');
    var logform = document.getElementById('logform');
    if (orderval.value == val) {
        if (orderdir.value == 'asc') {
            orderdir.value = 'desc';
        } else {
            orderdir.value = 'asc';
        }
    } else {
        orderval.value = val;
        orderdir.value = 'asc';
    }
    logform.submit();
}



function submit_sort_viewfiles(val)
{
    var orderval = document.getElementById('searchorder');
    var orderdir = document.getElementById('searchdir');
    var dir = document.getElementById('dir');
    if (orderval.value == val) {
        if (orderdir.value == 'asc') {
            orderdir.value = 'desc';
        } else {
            orderdir.value = 'asc';
        }
    } else {
        orderval.value = val;
        orderdir.value = 'asc';
    }
    show_files(dir.value, true);
}
function submit_viewfiles_page(offset)
{
    var offsetval = document.getElementById('offset');
    var dir = document.getElementById('dir');
    offsetval.value = offset;
    show_files(dir.value,false);
}
function submit_viewfiles_action_confirm(fileid, command, msg)
{
    var name = document.getElementById(fileid);
    if (name == null) return;
    name = name.value;
    msg = msg.replace('@@', name);
    var resp = confirm (msg);
    if (!resp) {return;}
    submit_viewfiles_action(fileid, command)
}
function submit_viewfiles_action(fileid, command)
{
    var challenge = document.getElementById('challenge');
    var xmlHttp=GetXmlHttpObject();
    var name = document.getElementById(fileid);
    var dir = document.getElementById('dir');
    if (name == null|| dir == null) return;
    name = name.value;
    dir = dir.value;
    var url="ajax_editviewfiles.php";
    var params = "cmd="+command+"&dir=" + encodeURIComponent(dir) + "&filename=" +encodeURIComponent(name) + "&challenge=" + encodeURIComponent(challenge.value)+"&sid="+Math.random();
    if (command != 'zip_dir') {
        xmlHttp.open("POST",url,true);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", params.length);
        xmlHttp.setRequestHeader("Connection", "close");

        xmlHttp.onreadystatechange= function() { 
            if (xmlHttp.readyState==4 && xmlHttp.status==200){
                show_files(dir, false);
                update_message_bar(xmlHttp);
            }
        };
        xmlHttp.send(params);
    } else {
        window.location = url+"?"+params;
    }

}
/*
function submit_viewfiles_action3(path, file, command, id)
{
    var action = document.getElementById('action');
    var id_elem = document.getElementById(id);
    var filename = document.getElementById('filename');
    var newname = document.getElementById('newname');
    newname.value = id_elem.value;
    action.value = command;
    filename.value = file;
    var searchform = document.getElementById('searchform');
    searchform.submit();
    }
function submit_viewfiles_action2(path, file, command, offset)
{
    var action = document.getElementById('action');
    var filename = document.getElementById('filename');
    action.value=command;
    filename.value=file;
    var searchform = document.getElementById('searchform');
    var offsetval = document.getElementById('offset');
    offsetval.value = offset;
    searchform.submit();
}
*/
function submit_delete_file(path, file)
{
    var action = document.getElementById('action');
    var filename = document.getElementById('filename');
    action.value='delete_file';
    filename.value=file;
    var searchform = document.getElementById('searchform');
    searchform.submit();
}
function submit_newsgroup_page(offset)
{
    var offsetval = document.getElementById('offset');
    var searchform = document.getElementById('searchngform');
    var oldsearch = document.getElementById('oldsearch');
    var newsearch = document.getElementById('newsearch');
    offsetval.value = offset;
    newsearch.value = oldsearch.value;  
    searchform.submit();
}
function submit_rssfeeds_page(offset)
{
    var offsetval = document.getElementById('offset');
    var searchform = document.getElementById('searchrssform');
    var oldsearch = document.getElementById('oldsearch');
    var newsearch = document.getElementById('newsearch');
    offsetval.value = offset;
    newsearch.value = oldsearch.value;  
    searchform.submit();
}
function submit_search(val, def)
{
    var orderval = document.getElementById('ng_search_order');
    var orderdirval = document.getElementById('ng_search_order_dir');
    var oldsearch = document.getElementById('oldsearch');
    var newsearch = document.getElementById('newsearch');
    if (orderval.value == val) {
        if (orderdirval.value == 'desc') {
            orderdirval.value = 'asc';
        } else {
            orderdirval.value = 'desc';
        }
    } else {
        orderdirval.value = def;
    }

    newsearch.value = oldsearch.value;  
    orderval.value = val;
    var searchform = document.getElementById('searchngform');
    searchform.submit();
}
function submit_rss_search(val, def)
{
    var orderval = document.getElementById('rss_search_order');
    var orderdirval = document.getElementById('rss_search_order_dir');
    var oldsearch = document.getElementById('oldsearch');
    var newsearch = document.getElementById('newsearch');
    if (orderval.value == val) {
        if (orderdirval.value == 'desc') {
            orderdirval.value = 'asc';
        }else{
            orderdirval.value = 'desc';
        }
    } else {
        orderdirval.value = def;
    }

    newsearch.value = oldsearch.value;  
    orderval.value = val;
    var searchform = document.getElementById('searchrssform');
    searchform.submit();
}


function submit_search_users(val, def)
{
    var orderval = document.getElementById('order');
    var orderdirval = document.getElementById('order_dir');
    if (orderval.value == val) {
        if (orderdirval.value == 'desc') {
            orderdirval.value = 'asc';
        }else{
            orderdirval.value = 'desc';
        }
    } else {
        orderdirval.value = def;
    }
    orderval.value = val;
    show_users(orderval.value, orderdirval.value);
}

function submit_search_jobs(val, def)
{
    var orderval = document.getElementById('order');
    var orderdirval = document.getElementById('order_dir');
    if (orderval.value == val) {
        if (orderdirval.value == 'desc') {
            orderdirval.value = 'asc';
        }else{
            orderdirval.value = 'desc';
        }
    } else {
        orderdirval.value = def;
    }
    orderval.value = val;
    load_jobs(orderval.value, orderdirval.value);
}


function submit_search_tasks(val, def)
{
    var orderval = document.getElementById('order');
    var orderdirval = document.getElementById('order_dir');
    if (orderval.value == val) {
        if (orderdirval.value == 'desc') {
            orderdirval.value = 'asc';
        }else{
            orderdirval.value = 'desc';
        }
    } else {
        orderdirval.value = def;
    }
    orderval.value = val;
    load_tasks(orderval.value, orderdirval.value);
}

function LoadTransfers()
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_showtransfers.php";
    url=url+"?sid="+Math.random();
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==4) { 
            var msg_id = document.getElementById('message_bar');
            show_content_div(xmlHttp, 'transfersdiv');
            var urdd_status = document.getElementById('urdd_status');
            var msg = document.getElementById('urdd_message');
            if (urdd_status.value == 0 && msg_id.innerHTML == '') {            
                msg_id.innerHTML = msg.value;
            }
            else if (urdd_status.value == 1 && msg_id.innerHTML == msg.value) {            
                msg_id.innerHTML = '';
            }

        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function UpdateTransfers()
{
    // call ajax, restart in 4 seconds
    LoadTransfers();
    setInterval('LoadTransfers()', 4000);
}


function show_content_div(xmlHttp, divid)
{
    if (xmlHttp.readyState==4) { 
        document.getElementById(divid).innerHTML = xmlHttp.responseText;
    }
}
function load_control()
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_admincontrol.php";
    url=url+"?sid="+Math.random();
    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'controldiv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function show_users(order, direction)
{        
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edit_users.php" + "?cmd=reload_users";
    url=url+"&sid="+Math.random();
    var orderval = document.getElementById('order');
    var orderdirval = document.getElementById('order_dir');
    if (order == null && orderval != null)
        order = orderval.value;
    if (order != null)
        url=url+"&sort="+order;

    if (direction == null && orderdirval != null)
        direction = orderdirval.value;
    if (direction != null)
        url=url+"&sort_dir="+direction;

    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'usersdiv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}

function show_files(curdir, reset_offset)
{
    var search = document.getElementById('search');
    var dir = document.getElementById('dir');
    var offset = document.getElementById('offset');
    var sort = document.getElementById('searchorder');
    var sortdir = document.getElementById('searchdir');
    if (search == null) search = ''; else search = search.value;
    if (offset == null || reset_offset == true) offset = 0; else offset = offset.value;
    if (sort == null) sort = ''; else sort = sort.value;
    if (sortdir == null) sortdir = ''; else sortdir = sortdir.value;
    if (dir == null) dir = ''; else dir = dir.value;
    if (curdir != null) dir = curdir;

    var xmlHttp=GetXmlHttpObject();
    var url="ajax_editviewfiles.php" + "?cmd=show_files";
    url = url + "&search=" + encodeURIComponent(search) + 
        "&offset=" + encodeURIComponent(offset) +
        "&sort=" + encodeURIComponent(sort) +
        "&dir=" + encodeURIComponent(dir) +
        "&sort_dir=" + encodeURIComponent(sortdir) ;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'viewfilesdiv');
            var dir = document.getElementById('dir2');
            var dir_top = document.getElementById('directory_top');
            dir_top.innerHTML = dir.value;
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}

function show_buttons()
{        
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edit_buttons.php" + "?cmd=show_buttons";
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'buttonsdiv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function show_usenet_servers()
{        
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edit_usenet_servers.php" + "?cmd=reload_servers";
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'usenetserversdiv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function show_post_message(groupid)
{        
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_post_message.php";
    url=url+"?sid="+Math.random();
    url=url+"&groupid="+groupid;
    url=url+"&cmd=show";
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_popup('postmessagediv','postmessage');
            show_content_div(xmlHttp, 'postmessagediv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function show_uploadnzb()
{        
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_show_upload.php";
    url=url+"?sid="+Math.random();
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'uploadnzbdiv');
            var item = document.getElementById("uploadnzbdiv");
            show_popup('uploadnzbdiv','uploadnzb');
            hide_popup('transferrenamediv', 'renametransfer');
            hide_popup('postdiv','post');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function ShowEditPost(postid)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_show_post.php?cmd=showrename&postid=" + postid;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            var item = document.getElementById("postdiv");
            item.innerHTML = xmlHttp.responseText;
            show_content_div(xmlHttp, 'postdiv');
            show_popup('postdiv','post');
            hide_popup('transferrenamediv', 'renametransfer');
            hide_popup('uploadnzbdiv', 'updloadnzb');

        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function show_post()
{        
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_show_post.php";
    url=url+"?sid="+Math.random();
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'postdiv');
            var item = document.getElementById("postdiv");
            show_popup('postdiv','post');
            hide_popup('transferrenamediv', 'renametransfer');
            hide_popup('uploadnzbdiv', 'updloadnzb');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function load_jobs(order, direction)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_adminjobs.php";
    url=url+"?sid="+Math.random();
    var orderval = document.getElementById('order');
    var orderdirval = document.getElementById('order_dir');
    if (order == null && orderval != null)
        order = orderval.value;
    if (order != null)
        url=url+"&sort="+order;

    if (direction == null && orderdirval != null)
        direction = orderdirval.value;
    if (direction != null)
        url=url+"&sort_dir="+direction;

    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'jobsdiv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function load_tasks(order, direction)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_admintasks.php";
    url=url+"?sid="+Math.random();
    var orderval = document.getElementById('order');
    var statusval = document.getElementById('status_select');
    var timeval = document.getElementById('time_select');
    var tasksearch = document.getElementById('tasksearch');
    var max_count = document.getElementById('max_count');
    var orderdirval = document.getElementById('order_dir');
    if (timeval != null ){
        timeval = timeval.options[timeval.selectedIndex].value;
        url=url+"&time="+timeval;
    }
    if (max_count != null && max_count.name != '_max_count'){
        max_count = max_count.value;
        url=url+"&max_count="+max_count;
    }
    if (tasksearch != null && tasksearch.name != '_search'){
        tasksearch = tasksearch.value;
        url=url+"&tasksearch="+tasksearch;
    }
    if (statusval != null){
        statusval = statusval.options[statusval.selectedIndex].value;
        url=url+"&status="+statusval;
    }
    if (order == null && orderval != null)
        order = orderval.value;
    if (order != null)
        url=url+"&sort="+order;

    if (direction == null && orderdirval != null)
        direction = orderdirval.value;
    if (direction != null)
        url=url+"&sort_dir="+direction;
    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            show_content_div(xmlHttp, 'tasksdiv');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function update_jobs()
{
    load_jobs();
    setTimeout('update_jobs()', 5000);
}



function update_tasks()
{
    load_tasks(null,null);
    setTimeout('update_tasks()', 5000);
}


function update_control()
{
    load_control();
    setTimeout('update_control()', 4000);
}


function ShowStatus(xmlHttp)
{
    if (xmlHttp.readyState==4) { 
        var content = xmlHttp.responseText;
        document.getElementById('urdstatus').innerHTML = content + '<br/>';
    }
}

function ReloadStatus(onoff)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_controltransfers.php?cmd=power" + onoff ;
    url=url+"&sid="+Math.random();
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}

function LoadStatus()
{
    var urdstatdiv = document.getElementById('urdstatus');
    var minimized = HasClass(urdstatdiv,'statusminimized');

    if (!minimized || urdstatdiv.innerHTML == '') {

        var xmlHttp=GetXmlHttpObject();
        var url="ajax_showstatus.php";
        url=url+"?sid="+Math.random();
        xmlHttp.onreadystatechange=function() {
            ShowStatus(xmlHttp);
        };
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null); 
    }
}

function UpdateStatus()
{
    // call ajax, restart in 10 seconds
    LoadStatus();
    setInterval('LoadStatus()', 4000);
}

function DisplaySetInfo(setid,xmlHttp)
{
    thediv = document.getElementById('div_'+setid);
    thediv.innerHTML = xmlHttp.responseText;
    thediv.className = "setinfo";
    thetr = document.getElementById('tr_set_'+setid);
    thetr.className = "";
    //set the last div id for reference so on reload we have it and can re-open 
        document.getElementById('lastdivid').value = setid;
}

function EditExtSetInfo(setid)
{
    // Do we clear or do we display?
    thediv = document.getElementById('QuickWindow');
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_showsetinfo.php?edit=1&setID="+encodeURIComponent(setid);

    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
                DisplaySetInfo(setid,xmlHttp);
        }
    };

    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}

function SearchButton(url, xname)
{
    var srch = (window.getSelection ? window.getSelection() : document.getSelection ? document.getSelection() : document.selection.createRange().text);
    srch = String(srch);
    if (srch === '') {
        alert("Please select the search query before clicking this button.");
    } else {
        /* Remove common separators: */
        srch = srch.replace(/[\]\[_"+.]/g,' ');
        url = url.replace(/\$q/,escape(srch));
        window.open(url,xname + 'window','');
    }
}
function ToggleRSS(id)
{
    var tracker = document.getElementsByName('rssfeed['+id+']');
    var curval = tracker[0].value;
    if (curval == 1) {
        tracker[0].value = 0;
    } else {
        tracker[0].value = 1;
    }
}

function ToggleNG(id)
{
    var tracker = document.getElementsByName('newsgroup['+id+']');
    var curval = tracker[0].value;
    if (curval == 1) {
        tracker[0].value = 0;
    }else {
        tracker[0].value = 1;
    }
}


function toggle_hide(id, class1)
{
    var elem = document.getElementById(id);
    ToggleClass2(elem, class1);
}


function markRead(setid, cmd, type)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_markread.php";
    url=url+"?cmd="+cmd+"&sid="+setid+"&type="+type;
    if (cmd == 'wipe') {
        challenge = document.getElementById('challenge');
        url = url + '&challenge=' + challenge.value;
    }
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            /* Only update display if backend succeeded: */
            if (cmd == 'markread') {
                thetr = document.getElementById('base_row_'+setid);
                ToggleClass(thetr,'markedread');
            }

            if (cmd == 'interesting') {
                thetr = document.getElementById('base_row_'+setid);
                ToggleClass(thetr,'interesting');
                var intimg = document.getElementById('intimg_'+setid);
                var buttonint = document.getElementById('buttonint').value;
                var buttonunint = document.getElementById('buttonunint').value;
                if (HasClass(thetr,'interesting')) {
                    intimg.src = buttonunint;
                } else {
                    intimg.src = buttonint;
                }
            }

            if (cmd == 'hide' || cmd == 'unhide') {
                thetr = document.getElementById('base_row_'+setid);
                ToggleClass(thetr,"hidden");
            }

            if (cmd == 'wipe') {
                challenge = document.getElementById('challenge');
                url = url + '&challenge=' + challenge.value;
                thetr = document.getElementById('base_row_'+setid);
                ToggleClass(thetr,'hidden');
            }
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}

function update_message_reload_transfers(xmlHttp)
{
    LoadTransfers();
    update_message_bar(xmlHttp);
}

function show_menu()
{
    var menu = document.getElementById('menu_table');
    var button = document.getElementById('close_window');
    remove_class(menu,"hidden");
    add_class(button,"hidden");
}

function hide_menu()
{
    var menu = document.getElementById('menu_table');
    var button = document.getElementById('close_window');
    add_class(menu,"hidden");
    remove_class(button,"hidden");
}


function post_edit(cmd, postid)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_editposts.php";
    var challenge = document.getElementById('challenge2');
    var params = "cmd="+cmd+"&postid="+postid+"&challenge="+challenge.value;
    SendXMLHTTPPOST(url, params, update_message_reload_transfers);
}



function TransferEdit(cmd, dlid)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edittransfers.php";
    var challenge = document.getElementById('challenge2');
    var params = "cmd="+cmd+"&dlid="+dlid+"&challenge="+challenge.value;
    SendXMLHTTPPOST(url, params, update_message_reload_transfers);
}

function Whichbutton(buttonval)
{
    var whichbutton = document.getElementById('whichbutton');
    whichbutton.value = buttonval;
    document.forms['setform'].submit();
}

function PreviewPopup(dlid, binary_id, group_id)
{
    newwindow = window.open("preview.php?dlid=" + dlid +"&binary_id="+binary_id +"&group_id="+group_id);
    if (window.focus) {
        newwindow.focus();
    }
}

function ShowPreview(xmlHttp)
{
    if (xmlHttp.readyState==4) { 
        document.getElementById('previewdiv').innerHTML = '<br/>' + xmlHttp.responseText;
    }
}


function LoadPreview(dlid, binary_id, group_id)
{
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_showpreview.php";
    url = url
        +"?dlid="+dlid
        +"&binary_id="+binary_id
        +"&group_id="+group_id
        +"&sid="+Math.random();
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            ShowPreview(xmlHttp);
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function UpdatePreview(dlid, binary_id, group_id)
{
    // Check if there is a input called 'redirect', if so redirect, else refresh.
    var redir = document.getElementById('redirect');
    if (redir !== null) {
        document.location.href = redir.value;
    } else {
        var do_reload = document.getElementById('do_reload');
        if (do_reload === null) {
            // call ajax, restart in 1 seconds
            LoadPreview(dlid, binary_id, group_id);
            previewtimer = setTimeout('UpdatePreview('+dlid+', "'+binary_id+'", '+group_id+')', 1000);
        }
    }
}


function select_preview(binid, gid)
{
    var chall = document.getElementById('challenge').value;
    
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_create_preview.php";
    var params="preview_bin_id="+binid+"&preview_group_id="+gid+"&challenge="+chall;
    xmlHttp.open("POST",url,true); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            var content = xmlHttp.responseText;
            if (!isNaN(content)) {
                PreviewPopup(content, binid, gid);
            } else {
                alert("Cannot open preview. "+content);
            }
        }
    };

    xmlHttp.send(params);
}

function update_message_bar(xmlHttp) 

{
    var msg_id = document.getElementById('message_bar');
    if (xmlHttp.responseText == "OK") {
        msg_id.innerHTML = '';
    } else {
        msg_id.innerHTML = xmlHttp.responseText;
    }
}

function TransfersButton(opt)
{
    if (opt == 'getnzb') {
        show_uploadnzb();
        return;
    } else if (opt =='post') {
        show_post();
        return;
    }

    // All other options require ajax:
    var challenge = document.getElementById('challenge1');
    var url="ajax_controltransfers.php";
    var params= "sid="+Math.random()+"&cmd="+opt+"&challenge="+challenge.value;
    SendXMLHTTPPOST(url, params, update_message_bar);
}


function AdminCommands(opt)
{
    var xmlHttp=GetXmlHttpObject();
    var challenge = document.getElementById('challenge_control');
    if (challenge == null)
        challenge = document.getElementById('challenge_status');
    var url="ajax_admincommands.php";
    var params = "sid="+Math.random()+"&action="+opt+"&challenge="+challenge.value;
    SendXMLHTTPPOST(url, params, null);
}


function buttons_action_confirm(action, uid, msg)
{
    var resp = confirm (msg);
    if (!resp) {return;}
    buttons_action(action, uid);
}   


function buttons_action(action, uid)
{
    var xmlHttp = GetXmlHttpObject();
    var challenge = document.getElementById('challenge_buttons');
    var url="ajax_edit_buttons.php";
    var params = "id="+uid+"&cmd="+encodeURIComponent(action) + "&challenge=" + challenge.value;
    params = params + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            if (action == 'edit') {
                var item = document.getElementById('buttoneditdiv');
                item.innerHTML = xmlHttp.responseText;
                show_popup('buttoneditdiv', 'editbutton');
            } else {
                show_buttons();
                var msg_id = document.getElementById('message_bar');

                if (xmlHttp.responseText == "OK") {
                    msg_id.innerHTML = '';
                } else {
                    msg_id.innerHTML = xmlHttp.responseText;
                }
            }
        };
    }
    xmlHttp.send(params);
}


function user_action_confirm(action, uid, msg)
{
    var resp = confirm (msg);
    if (!resp) {return;}
    user_action(action, uid);
}


function user_action(action, uid)
{
    var xmlHttp = GetXmlHttpObject();
    var challenge = document.getElementById('challenge');
    var url="ajax_edit_users.php";
    var params = "id="+uid+"&cmd="+encodeURIComponent(action) + "&challenge=" + challenge.value;
    params = params + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            if (action == 'edit') {
                var item = document.getElementById('usereditdiv');
                item.innerHTML = xmlHttp.responseText;
                show_popup('usereditdiv', 'edituser');
            } else {
                show_users();
                var msg_id = document.getElementById('message_bar');

                if (xmlHttp.responseText == "OK") {
                    msg_id.innerHTML = '';
                } else {
                    msg_id.innerHTML = xmlHttp.responseText;
                }
            }
        };
    }
    xmlHttp.send(params);
}


function usenet_action_confirm(action, uid, msg)
{
    var resp = confirm (msg);
    if (!resp) {return;}
    usenet_action(action, uid);
}


function usenet_action(action, uid)
{
    var xmlHttp = GetXmlHttpObject();
    var challenge = document.getElementById('challenge_usenet');
    var url="ajax_edit_usenet_servers.php";
    var params = "id="+uid+"&cmd="+action+ "&challenge=" + encodeURIComponent(challenge.value);
    params = params + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            show_usenet_servers();
            var msg_id = document.getElementById('message_bar');

            if (xmlHttp.responseText == "OK") {
                msg_id.innerHTML = '';
            } else {
                msg_id.innerHTML = xmlHttp.responseText;
            }

        };
    }
    xmlHttp.send(params);

}


function show_popup(itemname, baseclass)
{
    var item = document.getElementById(itemname);
    DisableClass(item, baseclass + 'off');
    EnableClass(item, baseclass + 'on');
}


function show_popup_remote(itemname, baseclass, referrer, command)
{
    var item = document.getElementById(itemname);

    var xmlHttp=GetXmlHttpObject();
    var url="ajax_import_settings.php";
    url=url+"?sid="+Math.random() +'&referrer='+ encodeURIComponent(referrer) ;
    if (command != null)
        url = url+'&cmd='+ encodeURIComponent(command) ;

    xmlHttp.onreadystatechange=function() {
    DisableClass(item, baseclass + 'off');
    EnableClass(item, baseclass + 'on');
        show_content_div(xmlHttp, itemname);
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null); 
}


function hide_popup(itemname, baseclass)
{
    var item = document.getElementById(itemname);
    DisableClass(item, baseclass + 'on');
    EnableClass(item, baseclass + 'off');
}


function ShowRenameTransfer(dlid)
{
    var item = document.getElementById('transferrenamediv');
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edittransfers.php?cmd=showrename&dlid=" + dlid;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            item.innerHTML = xmlHttp.responseText;
            show_popup('transferrenamediv','renametransfer');
            hide_popup('uploadnzbdiv', 'uploadnzb');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function edit_rss(id)
{
    var item = document.getElementById('rsseditdiv');

    var xmlHttp=GetXmlHttpObject();
    var url="ajax_editrss.php?cmd=showeditrss&id=" + id;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            item.innerHTML = xmlHttp.responseText;
            ToggleClass(item,'editrssoff');
            ToggleClass(item,'editrsson');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function edit_usenet_server(id)
{
    var item = document.getElementById('usenetservereditdiv');

    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edit_usenet_servers.php?cmd=showeditusenetserver&id=" + id;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            item.innerHTML = xmlHttp.responseText;
            ToggleClass(item,'editusenetserveroff');
            ToggleClass(item,'editusenetserveron');
        }
    };
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function switch_value(name)
{
    var item = document.getElementById(name);
    if (item.value == 'on') {
        item.value='off';
    } else {
        item.value='on';
    }
}


function update_rss()
{
    var item = document.getElementById('rsseditdiv');
    var id = document.getElementById('id');
    var rss_url = document.getElementById('rss_url');
    var rss_username = document.getElementById('rss_username');
    var rss_password = document.getElementById('rss_password');
    var rss_name = document.getElementById('rss_name');
    var rss_expire = document.getElementById('rss_expire');
    var rss_subscribed = document.getElementById('rss_subscribed');
    var challenge = document.getElementById('challenge');
    
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_editrss.php";
    var params = "cmd=update_rss&id=" + id.value + 
        "&rss_name=" + encodeURIComponent(rss_name.value) + 
        "&rss_url=" + encodeURIComponent(rss_url.value) + 
        "&rss_password=" + encodeURIComponent(rss_password.value) + 
        "&rss_username=" + encodeURIComponent(rss_username.value) + 
        "&rss_expire=" + encodeURIComponent(rss_expire.value) + 
        "&rss_subscribed=" + rss_subscribed.value +
        "&challenge=" + encodeURIComponent(challenge.value);
    params=params+"&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            ToggleClass(item,'editrssoff');
            ToggleClass(item,'editrsson');
            var url = document.location.href;
            window.location = url;
        }
    };
    xmlHttp.send(params);
}


function is_checked (item)
{
    if (item.checked) 
        return 'on';
    else
        return 'off';
}

function update_buttons()
{
    var item = document.getElementById('buttoneditdiv');
    var id = document.getElementById('id');
    var challenge = document.getElementById('challenge_editbuttons');
    var image_url = document.getElementById('image_url');
    var name = document.getElementById('name');
    var search_url = document.getElementById('search_url');
    var xmlHttp = GetXmlHttpObject();
    var url="ajax_edit_buttons.php";
    var params = "cmd=update_button&id=" + id.value + "&name=" + encodeURIComponent(name.value) + "&image_url=" + encodeURIComponent(image_url.value) + 
        "&search_url="+encodeURIComponent(search_url.value) + 
        "&challenge=" + encodeURIComponent(challenge.value);
    params = params + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            ToggleClass(item,'editbuttonoff');
            ToggleClass(item,'editbuttonon');
            show_buttons();
            var msg_id = document.getElementById('message_bar');
            if (xmlHttp.responseText == "OK") {
                msg_id.innerHTML = '';
            } else {
                msg_id.innerHTML = (xmlHttp.responseText);
            }

        };
    }
    xmlHttp.send(params);
}

//%27aoeua+aoeu@cgl12433456%5B098%21@%23%24%25%5E*%28%29%7B%7D%5B%5D/%3D%3F%7C+s-S_ZV%27%2C.%3C%3E%27%22
//'aoeua%2Baoeu%40cgl12433456%5B098!%40%23%24%25%5E*()%7B%7D%5B%5D%2F%3D%3F%7C%2Bs-S_ZV'%2C.%3C%3E'%22
function update_user()
{
    var item = document.getElementById('usereditdiv');
    var id = document.getElementById('id');
    var challenge = document.getElementById('challenge');
    var username = document.getElementById('username');
    var fullname = document.getElementById('fullname');
    var email = document.getElementById('email');
    var password = document.getElementById('password');
    var isactive = is_checked(document.getElementById('isactive'));
    var autodownload = is_checked(document.getElementById('autodownload'));
    var seteditor = is_checked(document.getElementById('seteditor'));
    var post = is_checked(document.getElementById('post'));
    var isadmin = is_checked(document.getElementById('isadmin'));
    var test = "'aoeua+aoeu@cgl12433456[098!@#$%^*(){}[]/=\?|+s-S_ZV',.<>'\"";
    var xmlHttp = GetXmlHttpObject();
    var url="ajax_edit_users.php";
    var params = "cmd=update_user&id=" + id.value + "&username=" + encodeURIComponent(username.value) +  "&password=" + encodeURIComponent(password.value) + 
        "&fullname="+encodeURIComponent(fullname.value) + 
        "&email="+encodeURIComponent(email.value) + 
        "&isactive="+encodeURIComponent(isactive) + 
        "&post="+encodeURIComponent(post) + 
        "&isadmin="+encodeURIComponent(isadmin) + 
        "&autodownload="+encodeURIComponent(autodownload) + 
        "&seteditor="+encodeURIComponent(seteditor) + 
        "&challenge=" + encodeURIComponent(challenge.value);
    params = params + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            ToggleClass(item,'edituseroff');
            ToggleClass(item,'edituseron');
            show_users();
            var msg_id = document.getElementById('message_bar');
            if (xmlHttp.responseText == "OK") {
                msg_id.innerHTML = '';
            } else {
                msg_id.innerHTML = (xmlHttp.responseText);
            }

        };
    }
    xmlHttp.send(params);
}


function update_usenet_server()
{
    var item = document.getElementById('usenetservereditdiv');
    var id = document.getElementById('id');
    var challenge = document.getElementById('challenge');
    var name = document.getElementById('name');
    var port = document.getElementById('port');
    var sec_port = document.getElementById('sec_port');
    var hostname = document.getElementById('hostname');
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var authentication = document.getElementById('needauthentication');
    var priority = document.getElementById('priority');
    var retention = document.getElementById('retention');
    var connection = document.getElementById('connection');
    var compressed_headers = document.getElementById('compressed_headers');
    var threads = document.getElementById('threads');
    var posting = document.getElementById('posting');
    var checked = authentication.checked;
    if (checked)
        authentication = 'on';
    else
        authentication = 'off'
    checked = compressed_headers.checked;
    if (checked)
        compressed_headers = 'on';
    else
        compressed_headers = 'off'

    checked = posting.checked;
    if (checked)
        posting = 'on';
    else
        posting = 'off'
    var xmlHttp = GetXmlHttpObject();
    var url="ajax_edit_usenet_servers.php";
    var params = "cmd=update_usenet_server&id=" + id.value + "&name=" + encodeURIComponent(name.value) + "&hostname=" + encodeURIComponent(hostname.value) + "&username=" + encodeURIComponent(username.value) + 
        "&port=" + encodeURIComponent(port.value) + "&secure_port=" + encodeURIComponent(sec_port.value) + "&password=" + encodeURIComponent(password.value) + "&authentication=" + encodeURIComponent(authentication) + 
        "&priority=" + encodeURIComponent(priority.value) + "&connection=" + encodeURIComponent(connection.value) + "&threads=" + encodeURIComponent(threads.value) + "&challenge=" + encodeURIComponent(challenge.value) + "&retention=" + encodeURIComponent(retention.value)+ "&compressed_headers=" + encodeURIComponent(compressed_headers) + "&posting=" + encodeURIComponent(posting);
    params = params + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            ToggleClass(item,'editusenetserveroff');
            ToggleClass(item,'editusenetserveron');
            var url = document.location.href;
            show_usenet_servers();
            update_message_bar(xmlHttp)
        };
    }
    xmlHttp.send(params);
}


function post_message()
{
    hide_popup('postmessagediv', 'postmessage');
    var subject = document.getElementById('subject');
    var postername = document.getElementById('postername');
    var posteremail = document.getElementById('posteremail');
    var groupid = document.getElementById('groupid');
    var challenge = document.getElementById('challenge1');
    var message = document.getElementById('messagetext');
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_post_message.php";
    var params = "cmd=post&subject=" + encodeURIComponent(subject.value)
        + "&postername=" + encodeURIComponent(postername.value)
        + "&posteremail=" + encodeURIComponent(posteremail.value)
        + "&message=" + encodeURIComponent(message.value)
        + "&groupid=" + encodeURIComponent(groupid.options[groupid.selectedIndex].value)
        + "&challenge=" + encodeURIComponent(challenge.value)  
        + "&sid="+Math.random();
    
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            update_message_reload_transfers(xmlHttp)
        }
    }
    xmlHttp.send(params);
}


function create_post()
{
    hide_popup('postdiv', 'post');
    var subject = document.getElementById('subject');
    var postername = document.getElementById('postername');
    var posteremail = document.getElementById('posteremail');
    var recovery = document.getElementById('recovery');
    var filesize = document.getElementById('filesize');
    var postid = document.getElementById('postid');
    var groupid = document.getElementById('groupid');
    var directory = document.getElementById('directory');
    var delete_files = document.getElementById('delete_files');
    var timestamp = document.getElementById('timestamp');
    var challenge = document.getElementById('challenge1');
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_process_post.php";
    var params = "cmd=post&subject=" + encodeURIComponent(subject.value)
        + "&postername=" + encodeURIComponent(postername.value)
        + "&posteremail=" + encodeURIComponent(posteremail.value)
        + "&delete_files=" + encodeURIComponent(delete_files.value)
        + "&recovery=" + encodeURIComponent(recovery.value)
        + "&groupid=" + encodeURIComponent(groupid.options[groupid.selectedIndex].value)
        + "&directory=" + encodeURIComponent(directory.options[directory.selectedIndex].value)
        + "&postid=" + encodeURIComponent(postid.value)
        + "&filesize=" + encodeURIComponent(filesize.value)
        + "&challenge=" + encodeURIComponent(challenge.value)  
        + "&timestamp=" + encodeURIComponent(timestamp.value)
        + "&sid="+Math.random();
    
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            update_message_reload_transfers(xmlHttp)
        }
    }
    xmlHttp.send(params);
}


function RenameTransfer()
{
    var item = document.getElementById('transferrenamediv');
    var dlid = document.getElementById('dlid');
    var dlname = document.getElementById('dlname');
    var dlpass = document.getElementById('dlpass');
    var unrar = document.getElementById('unrar');
    var unpar = document.getElementById('unpar');
    var subdl = document.getElementById('subdl');
    var starttime = document.getElementById('starttime');
    var deletef = document.getElementById('delete_files');
    var challenge = document.getElementById('challenge3');
    
    var xmlHttp=GetXmlHttpObject();
    var url="ajax_edittransfers.php";
    var params = "cmd=rename&dlid=" + dlid.value 
        + "&dlname=" +  encodeURIComponent(dlname.value)
        + "&dlpass=" +  encodeURIComponent(dlpass.value)
        + "&delete=" +  encodeURIComponent(deletef.value)
        + "&unrar=" +  encodeURIComponent(unrar.value)
        + "&subdl=" +  encodeURIComponent(subdl.value)
        + "&unpar=" +  encodeURIComponent(unpar.value)
        + "&starttime=" +  encodeURIComponent(starttime.value)
        + "&challenge=" + encodeURIComponent(challenge.value)
        + "&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200) {
            ToggleClass(item,'renametransferoff');
            ToggleClass(item,'renametransferon');
            update_message_reload_transfers(xmlHttp)
        }
    };
    xmlHttp.send(params);
}


function test_search_button(url, xname)
{
    url = url.replace(/\$q/,encodeURIComponent("test"));
    window.open(url,xname + 'window','');
}


function do_submit_group( name, group)
{
    var groupid = document.getElementById('select_groupID');
    groupid.value = group;
    do_submit(name);
}


function do_submit_feed( name, feed)
{
    var feedid = document.getElementById('select_feedid');
    feedid.value = feed;
    do_submit(name);
}


function do_submit(name)
{
    var searchform = document.getElementById(name);
    searchform.submit();
}


function open_in_window(url, use_new)
{
    if (use_new) {
        window.open(url);
    } else {
        window.location = url;
    }
}


function view_files_follow_link(e, type, fileid)
{
    var name = document.getElementById(fileid);
    var dir = document.getElementById('dir');
    if (name == null || dir == null) return false;
    name = name.value;
    dir = dir.value;
    var path = encodeURIComponent(dir+name);
    if (e.which == 3) 
        return false;
    if (type == 'dir') {
        open_in_window ('viewfiles.php?dir=' + path, e.which == 2 );
    } else {
        open_in_window( 'getfile.php?file=' + path, e.which == 2);
    }
    return true;
}


function rename_file_form(fileid)
{
    var challenge = document.getElementById('challenge');
    var name = document.getElementById(fileid);
    var dir = document.getElementById('dir');
    if (name == null|| dir == null) return;
    name = name.value;
    dir = dir.value;

    var xmlHttp=GetXmlHttpObject();
    var url="ajax_editviewfiles.php";
    var params = "cmd=show_rename&dir=" + encodeURIComponent(dir) + "&filename=" +encodeURIComponent(name) + "&challenge=" + encodeURIComponent(challenge.value)+"&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            show_content_div(xmlHttp, 'fileeditdiv');
            show_popup('fileeditdiv','editfile');
        }
    };
    xmlHttp.send(params);
}


function update_filename()
{
    var xmlHttp=GetXmlHttpObject();
    var challenge = document.getElementById('challenge_editfile');
    var directory = document.getElementById('directory_editfile');
    var oldfilename = document.getElementById('oldfilename_editfile');
    var newfilename = document.getElementById('newfilename_editfile');
    var rights = document.getElementById('rights_editfile');
    var group = document.getElementById('group_editfile');
    var url="ajax_editviewfiles.php";
    var params = "cmd=do_rename&dir=" + encodeURIComponent(directory.value) 
        + "&oldfilename=" +encodeURIComponent(oldfilename.value)
        + "&newfilename=" +encodeURIComponent(newfilename.value)
        + "&challenge=" + encodeURIComponent(challenge.value)
        + "&rights=" + encodeURIComponent(rights.value)
        + "&group=" + encodeURIComponent(group.value)
        +"&sid="+Math.random();
    xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            hide_popup('fileeditdiv','editfile');
            show_files(directory.value, false);

            update_message_bar(xmlHttp);
        }
    };
    xmlHttp.send(params);
}


function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}


function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) { 
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }else if (obj.y){
        curtop += obj.y;
    }
    return curtop;
}


function ScrollOnReload(scrval)
{
    //check to make sure our variable is not null and has a value
    if (scrval) {
        //move the page down to the open div
        document.getElementById('contentout').scrollTop=scrval;
    }
}


function UpdateQuickMenuImages()
{
    // Loop all "quickmenuitem_x" divs:
    var themaindiv = document.getElementById('QuickMenu');
    var divwidth = themaindiv.offsetWidth;
    var divheight = themaindiv.offsetHeight;

    // Assuming 40x40
    var picsize = 40;

    var middlex = (divwidth / 2);
    var middley = (divheight / 2);

    // Number of items to show:
    var quicks = document.getElementById('nrofquickmenuitems').value;

    // Distance (radius): 
    // Radius depends on the picsize (assuming circle, so width = diameter), using 50% margins on the sides
    // Circumference == diameter * 1.5 * nr of buttons
    // 2piR = quicks * 40 * 1.5
    // R = qu

    // The distance between images needs to be bigger for low nr of images, because of the [x] button in between
    // For 1 or 2 buttons, use distance of 3 (1 would otherwise be in the middle, 2 right above eachother)
    var minquicks = Math.max(quicks,3);
    var distancefactor = 2.2 - (minquicks / 5);
    distancefactor = Math.max(distancefactor,1);

    var radius = Math.round(minquicks * picsize * distancefactor  / (2 * Math.PI));

    var rad2deg = Math.PI/180;

    for (var i = 1; i <= quicks; i++) {
        var thediv = document.getElementById('quickmenuitem_' + i);
        var angle = 360 / quicks * (i - 1);
        angle = angle - 90;
        var offsetx = Math.round(radius * Math.cos(angle * rad2deg));
        var offsety = Math.round(radius * Math.sin(angle * rad2deg));
        thediv.style.left = middlex + offsetx - (picsize / 2) + 'px';
        thediv.style.top = middley + offsety - (picsize / 2) + 'px';
    }
    // And set the close thingy:
    thediv = document.getElementById('quickmenuitem_close');
    divwidth = thediv.offsetWidth;
    divheight = thediv.offsetHeight;
    thediv.style.left = middlex - (divwidth/2) + 'px';
    thediv.style.top = middley - (divheight/2) + 'px';
}


function CloseQuickDisplay()
{
        var thediv = document.getElementById('QuickWindow');
    thediv.scrollTop=0;
        DisableClass(thediv,'QuickWindow');
        EnableClass(thediv,'QuickWindowHidden');
}


function CloseQuickMenu()
{
    var thediv = document.getElementById('QuickMenu');
    DisableClass(thediv,'QuickMenu');
    EnableClass(thediv,'QuickMenuHidden');
}


function CloneObject(obj)
{
    var newObj = new Object();
    for (prop in obj) {
        newObj[prop] = obj[prop];
    }
    return newObj;
}


function ShowQuickMenu(type,subject,srctype, e)
{
    var rightclick;
    if (!e) {e = window.event;}

    else if (e.which) {rightclick = (e.which == 3);}
    else if (e.button) {rightclick = (e.button == 2);}

    // We don't show the quickmenu if it was a right mouse button
    if (rightclick) { return false; }
    // Nor if there's a mouse button pressed.. we'll wait till the user lets go:
    if (mousedown) { return false; }

    CloseQuickDisplay();

    // Create an overlay div
    var thediv = document.getElementById('QuickMenu');
    EnableClass(thediv,'QuickMenu');
    DisableClass(thediv,'QuickMenuHidden');

    // Fill menu
        var xmlHttp=GetXmlHttpObject();
        var url="ajax_showquickmenu.php";
        url=url+"?type="+type+"&srctype="+srctype+"&subject="+subject+"&random="+Math.random();
        xmlHttp.onreadystatechange=function() {
                if (xmlHttp.readyState==4 && xmlHttp.status==200) {
                        thediv.innerHTML = xmlHttp.responseText;
            UpdateQuickMenuImages();
                }
        };
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);

    // Loading.
    thediv.innerHTML = "";

    // Make sure it's displayed around the cursor:
    var posx = 0;
    var posy = 0;

    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    // Sizes:
    var divwidth = thediv.offsetWidth;
    var divheight = thediv.offsetHeight;

    var newdivleft = posx - (divwidth / 2);
    var newdivtop = posy - (divheight / 2);

    // Make sure we don't exceed edges:
    if (newdivleft < 0) {newdivleft = 0;}
    if (newdivleft + divwidth > document.body.offsetWidth) {newdivleft = document.body.offsetWidth - divwidth;}
    if (newdivtop < 0) {newdivtop = 0;}

    thediv.style.left = newdivleft + 'px';
    thediv.style.top = newdivtop + 'px';
    return true;
}


function ShowQuickDisplay(srctype,subject,e, type)
{
    CloseQuickMenu();

    // Create an overlay div
    var thediv = document.getElementById('QuickWindow');
    EnableClass(thediv,'QuickWindow');
    DisableClass(thediv,'QuickWindowHidden');

    // Fill menu
        var xmlHttp=GetXmlHttpObject();
        var url="ajax_showquickdisplay.php";
        url=url+"?type="+type+"&srctype="+srctype+"&subject="+subject+"&random="+Math.random();
        xmlHttp.onreadystatechange=function() {
                if (xmlHttp.readyState==4 && xmlHttp.status==200) {
                        thediv.innerHTML = xmlHttp.responseText;
                }
        };
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    // Loading.
    thediv.innerHTML = "...";
}


function GuessExtSetInfoSafe(setID, type)
{
    var setname = (window.getSelection ? window.getSelection() : document.getSelection ? document.getSelection() : document.selection.createRange().text);
    setname = String(setname);
    if (setname === '') {
        alert("Please select the set name before clicking this button.");
    }else{
        var xmlHttp=GetXmlHttpObject();
        var url="ajax_showquickdisplay.php";
        url=url+"?srctype=setguessesisafe&subject="+setID+"&type="+type+"&setname="+setname+"&random="+Math.random();
        xmlHttp.onreadystatechange=function() {
            if (xmlHttp.readyState==4 && xmlHttp.status==200) {
                ShowQuickDisplay('seteditesi',setID,'', type);
            }
        };
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);

    }
}


function Reload()
{
    //window.location.href=window.location.href;
    //history.go(0);
    // Only one that seems to work:
//  window.location.reload();
    var url = document.location.href;       
    window.location = url;
}


function GuessBasketExtSetInfo(setID, type)
{
    var setname = (window.getSelection ? window.getSelection() : document.getSelection ? document.getSelection() : document.selection.createRange().text);
    setname = String(setname);
    if (setname === '') {
        alert("Please select the set name before clicking this button.");
    }else{
        var xmlHttp=GetXmlHttpObject();
        var url="ajax_showquickdisplay.php";
        url=url+"?srctype=setbasketguessesi&subject=undefined&type=undefined&setname="+setname+"&random="+Math.random();
        xmlHttp.onreadystatechange=function() {
            if (xmlHttp.readyState==4 && xmlHttp.status==200) {
                // Reload to show the new info:
                Reload();
                //alert("reloaded?");
                CloseQuickMenu();
            }
        };
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }
    return true;
}


function GuessExtSetInfo(setID, type)
{
    var setname = (window.getSelection ? window.getSelection() : document.getSelection ? document.getSelection() : document.selection.createRange().text);
    setname = String(setname);
    if (setname === '') {
        alert("Please select the set name before clicking this button.");
    }else{
        var xmlHttp=GetXmlHttpObject();
        var url="ajax_showquickdisplay.php";
        url=url+"?srctype=setguessesi&subject="+setID+"&type="+type+"&setname="+setname+"&random="+Math.random();
        xmlHttp.onreadystatechange=function() {
            if (xmlHttp.readyState==4 && xmlHttp.status==200) {
                CloseQuickMenu();
                // Also echo the new setname into the TD:
                var thetd = document.getElementById('td_set_' + setID);
                if ( xmlHttp.responseText != '')
                    thetd.innerHTML = xmlHttp.responseText;
            }
        };
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);

    }
}


function SaveExtSetBinaryType(setID,sel, srctype, type)
{
    var binarytype = sel.options[sel.selectedIndex].value;
    var xmlHttp = GetXmlHttpObject();
    var url="ajax_showquickdisplay.php";
    var params = "srctype=setsavebintype&subject=" + setID +"&type="+type+ "&values[binarytype]=" + binarytype;
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            ShowQuickDisplay('seteditesi',setID,'', type);
        }
    };
    xmlHttp.send(params);
}


function SaveExtSetInfo(setID, type)
{
    var formname = 'ext_setinfo_' + setID;
    var theform = document.getElementById('ext_setinfo_'+setID);

    var xmlHttp = GetXmlHttpObject();
    var url="ajax_showquickdisplay.php";
    var params = "srctype=setsaveesi&subject=" + setID+"&type="+type;
    for(i=0; i<document.forms[formname].elements.length; i++) {
        var checked = document.forms[formname].elements[i].checked;
        if ((document.forms[formname].elements[i].type == 'checkbox' && checked === true) || (document.forms[formname].elements[i].type != 'checkbox')) {
            params = params + '&' + encodeURIComponent(document.forms[formname].elements[i].name) + '=' + encodeURIComponent(document.forms[formname].elements[i].value);
        }
    }
    xmlHttp.open("POST", url, true);

    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
            CloseQuickDisplay();
            // Also echo the new setname into the TD:
            var thetd = document.getElementById('td_set_' + setID);
            if ( xmlHttp.responseText != '')
                thetd.innerHTML = xmlHttp.responseText;

        }
    };
    xmlHttp.send(params);
}


function toggle_menu()
{
    var urdstatdiv = document.getElementById('menu_table');
    var showmenu = document.getElementById('show_menu_div');
    var hidemenu = document.getElementById('hide_menu_div');
    ToggleClass(urdstatdiv,'hidden');
    ToggleClass(showmenu,'hidden');
    ToggleClass(hidemenu,'hidden');

    if (HasClass(urdstatdiv,'hidden')) {
        var xmlHttp = SendXMLHTTPGET('ajax_processgeneric.php?command=setmenudisplay&arg=0',null);
    } else {
        var xmlHttp = SendXMLHTTPGET('ajax_processgeneric.php?command=setmenudisplay&arg=1',null);
    }
}


function ToggleStatusWindow()
{
    var urdstatdiv = document.getElementById('urdstatus');
    ToggleClass(urdstatdiv,'statusminimized');

    if (HasClass(urdstatdiv,'statusminimized')) {
        var xmlHttp = SendXMLHTTPGET('ajax_processgeneric.php?command=setstatusdisplay&arg=0',null);
    } else {
        var xmlHttp = SendXMLHTTPGET('ajax_processgeneric.php?command=setstatusdisplay&arg=1',null);
    }
}


function FinishCheckStatusWindow(xmlHttp)
{
    var urdstatdiv = document.getElementById('urdstatus');
    var hasit = HasClass(urdstatdiv,'statusminimized');

    if (xmlHttp.responseText == '1') { var needsit = false; } // Doesn't need minimization
    if (xmlHttp.responseText == '0') { var needsit = true; }  // Needs minimization

    if (hasit != needsit) ToggleClass(urdstatdiv,'statusminimized');
}

function CheckStatusWindow()
{
    SendXMLHTTPGET('ajax_processgeneric.php?command=getstatusdisplay',FinishCheckStatusWindow);
}


function reload_screen(xmlHttp)
{
    var url = window.location.href;
    window.location = url;
}

function remove_rss(id, msg)
{
    var resp = confirm (msg);
    if (!resp) {return;}
    var challenge = document.getElementById('challenge_main');
    SendXMLHTTPPOST('ajax_editrss.php', 'cmd=delete&id='+id+'&challenge='+encodeURIComponent(challenge.value),reload_screen);
}
            

function confirm_delete_account(id, msg)
{
    var box_ = document.getElementsByName('delete_account');
    var box = box_[0];
    if (box.checked == false) { // checkbox gets set before the onclick is called
        box.checked = false;
        return false;
    }

    var resp = confirm (msg);
    if (resp == true) {
        var the_form = document.getElementById('settings_form');
        box.checked = true;
        the_form.submit();
    } else {
        box.checked = false;
    }
    return true;
}


function fold_transfer(id, type)
{
	// id = global or ready/active/finished/error/etc...
	// type = down/post
	SendXMLHTTPGET('ajax_update_session.php?var='+encodeURIComponent(id)+'&type='+encodeURIComponent(type)+'&sid='+Math.random(), null);
	ToggleClassById(id + type,'dynimgplus');
	ToggleClassById(id + type,'dynimgminus');

	if (type == 'post'){
	//	var img_src = document.getElementById('plus_post_'+id);
	//	var tbody_src = document.getElementById('data_post_'+id);
		ToggleClassById('data_post_'+id, 'hidden');
	} else {
	//	var img_src = document.getElementById('plus_down_'+id);
	//	var tbody_src = document.getElementById('data_down_'+id);
		ToggleClassById('data_down_'+id, 'hidden');
	}
/*
	var src = img_src.src;
	if (src.match('icon_triangle_up') != null)
		src = src.replace(/icon_triangle_up/, 'icon_triangle_down');
	else 
		src = src.replace(/icon_triangle_down/, 'icon_triangle_up');
	img_src.src = src;
*/

}

function ToggleGroupOfSets(startset,stopset,type)
{
    var sets = document.getElementsByName("setdata[]");
    var inrange = false;

    for (var i = 0; i < sets.length; i++) {
        // We want to toggle the last set as well, but definitely not the first one 
        // (it got toggled when the user clicked it, don't toggle it back)

        // Also, setdata[] stuff always starts with "set_"!
        thissetvalue = sets[i].id.substr(4);

        // startset was pre-toggled, untoggle so we don't have to worry about it:
        if (thissetvalue == startset) {
            ToggleSet(thissetvalue, type);
        }

        // We'll allow the start/stop sets to be reversed... robustness pwnz.
        if (thissetvalue == startset || thissetvalue == stopset) {
            if (inrange == false) {
                inrange = true;
            } else {
                inrange = false;
                // Last one, needs to be toggled but won't be because it's now out of range:
                ToggleSet(thissetvalue, type);
            }
        }

        // If in range, toggle:
        if (inrange == true) {
            ToggleSet(thissetvalue, type);
        }
    }
}


function fold_adv_search()
{/*
    var adv_search = document.getElementById("adv_search");
    var img_adv_search = document.getElementById("img_adv_search");
    var src = img_adv_search.src;
    if (src.match('icon_triangle_up') != null) {
        src = src.replace(/icon_triangle_up/, 'icon_triangle_down');
    } else {
        src = src.replace(/icon_triangle_down/, 'icon_triangle_up');
    }
    img_adv_search.src = src;
   */
    ToggleClassById('adv_search_button','dynimgplus');
	ToggleClassById('adv_search_button','dynimgminus');
    ToggleClassById('adv_search', 'hidden');
}


function clear_form(formIdent) { 
    var form = document.getElementById(formIdent);
    for (var y = 0 ; y < form.elements.length; y++) {
        type = form.elements[y].type;
        switch(type){
            case "text":
            case "textarea":
            case "password":
                form.elements[y].value = "";
            break;
            case "radio":
            case "checkbox":
                form.elements[y].checked = "";
            break;
            case "select-one":
                form.elements[y].options[0].selected = true;
            break;
            case "select-multiple":
                for (z=0; z<form.elements[y].options.length; z++){
                    form.elements[y].options[z].selected = false;
                }
            break;
        }
    }
}


function do_keypress_viewfiles(e)
{
    var keycode;
    if (window.event) { keycode = window.event.keyCode; }
    else if (e) { keycode = e.which; }
    else { return true;}
    if (keycode == 13) {
        show_files(null, true);
    }
    return true;
}


function collapse_select(name, par)
{
 //   var image = document.getElementById(name+'_collapse');
    var orig_size = document.getElementById(name+'_orig_size');
    var sel = document.getElementById(name+'_select');
    var size;
    if (par == 'size') {
        size = sel.size;
    } else if (par == 'rows') {
        size = sel.rows ;
    }
//    var src = image.src;
    if (size >= orig_size.value) {
        size = 2;
  //      src = src.replace(/icon_triangle_up/, 'icon_triangle_down');
        ToggleClassById(name+'_collapse','dynimgminus');
        ToggleClassById(name+'_collapse','dynimgplus');
    } else {
        size = orig_size.value;
//        src = src.replace(/icon_triangle_down/, 'icon_triangle_up');
        ToggleClassById(name+'_collapse','dynimgminus');
        ToggleClassById(name+'_collapse','dynimgplus');
    }
//    image.src = src;

    if (par == 'size') {
        sel.size = size;
    } else if (par == 'rows') {
        sel.rows = size;
    }

}

function submit_language_login()
{
    var lang = document.getElementById('language_select');
    var curr_language = document.getElementById('curr_language');
    var myform = document.getElementById('urd_login_form');
    if (lang != null ) {
        var langval = lang.options[lang.selectedIndex].value;
        if (curr_language == null || curr_language.value != langval) {
            curr_language_value = langval;
            myform.submit();
        }
    }
}

function submit_config()
{
    var level = document.getElementById('pref_level_select');
    var cur_level = document.getElementById('current_pref_level');
    var myform = document.getElementById('settings_form');
    if (level != null ) {
        level = level.options[level.selectedIndex].value;
        if (cur_level == null || cur_level.value != level) {
            myform.submit();
        }
    }
}


function clean_input(id, name)
{
    var input = document.getElementById(id);
    if (input != null && input.name != name){
        input.value = "";
        var newname = input.name;
        newname = newname.replace("_", "");
        input.name = newname;
    }
}


